﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Net.Http;
using System.Windows.Forms;
using BaseTest;
using FBroSharp;
using FBroSharp.DataType;
using FBroSharp.Lib;

namespace 网页请求置入Cookie
{
    public partial class Form1 : Form
    {
        private static readonly HttpClient client = new HttpClient();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Width = 1050;
            Height = 600;
            CreateBrowser("https://www.baidu.com");
        }

        public void CreateBrowser(string url) { 
            BrowserEvent browserEvent= new BrowserEvent();
            FBroSharpWindowsInfo window_info = new FBroSharpWindowsInfo
            { 
                parent_window = this.Handle,
                width = this.ClientSize.Width,
                height = this.ClientSize.Height,
                x = 0,
                y = 0,
            };
            FBroSharpControl.CreatBrowser(url,window_info,default,default, default, browserEvent,default);

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < BrowserList.data.Count; i++)
            { 
                BrowserList.data[i].MoveWindow(0, 0, this.Width, this.Height,true);
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            FBroSharpBrowser browser = BrowserList.data[0];
            string url = "https://www.xiaohongshu.com"; // 确保 URL 是完整的
            string json = await GetJsonAsync();

            if (json != null)
            {
                SetCookiesFromJson(browser, url, json,true);
                MessageBox.Show("设置 Cookie 成功。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("无法获取 JSON 数据。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private async Task<string> GetJsonAsync()
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("http://127.0.0.1/ck.json");
                response.EnsureSuccessStatusCode(); // 确保请求成功
                string json = await response.Content.ReadAsStringAsync();
                Console.WriteLine("获取到 JSON 数据: " + json);
                return json;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("请求失败: " + e.Message);
                return null; // 或者根据需要返回默认值
            }
        }
        // 方法定义
        public static void SetCookiesFromJson(FBroSharpBrowser browser, string url, string json, bool loadurl=false)
        {
            // 手动解析 JSON 字符串
            List<FBroSharpCookieData> cookies = new List<FBroSharpCookieData>();

            // 使用 System.Text.Json 进行手动解析
            var jsonArray = JsonSerializer.Deserialize<List<JsonElement>>(json);

            foreach (var item in jsonArray)
            {
                var cookie = new FBroSharpCookieData
                {
                    domain = item.GetProperty("domain").GetString(),
                    httponly = item.GetProperty("httpOnly").GetBoolean(),
                    name = item.GetProperty("name").GetString(),
                    value = item.GetProperty("value").GetString(),
                    path = item.GetProperty("path").GetString(),
                    
                };

                cookies.Add(cookie);
            }

            // 打印结果以验证
            foreach (var cookie in cookies)
            {
                Console.WriteLine($"Domain: {cookie.domain}, Name: {cookie.name}, Value: {cookie.value}");
            }

            if (cookies == null || cookies.Count == 0)
            {
                Console.WriteLine("没有有效的cookie数据。");
                return;
            }

            // 获取 CookieManager
            FBroSharpCookieManager manager = (FBroSharpCookieManager)browser.GetRequestContext().GetCookieManager();

            // 遍历每个cookie并设置
            foreach (var cookie in cookies)
            {             
                manager.SetCookie(url, cookie);
            }
            if (loadurl)
            { 
                browser.GetMainFrame().LoadURL(url);
            }
        }
    }
}
